// pages/user-add/user-add.js
Page({
    data: {
      username: '',
      password: '',
      role: '普通用户',
    },
  
    onUsernameInput(e) {
      this.setData({ username: e.detail.value });
    },
  
    onPasswordInput(e) {
      this.setData({ password: e.detail.value });
    },
  
    onRoleChange(e) {
      const roles = ['普通用户', '管理员'];
      this.setData({ role: roles[e.detail.value] });
    },
  
    handleSubmit() {
      const { username, password, role } = this.data;
  
      if (!username || !password) {
        wx.showToast({
          title: '请输入用户名和密码',
          icon: 'none',
          duration: 1500,
        });
        return;
      }
  
      const app = getApp();
      const db = app.globalData.db;
  
      // 向云数据库插入新用户
      db.collection('users').add({
        data: {
          username,
          password,
          role: role === '管理员' ? 'admin' : 'user',
          createdAt: new Date(), // 记录创建时间
        },
        success: () => {
          wx.showToast({
            title: '新增用户成功',
            icon: 'success',
            duration: 1500,
          });
  
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        },
        fail: (err) => {
          wx.showToast({
            title: '新增用户失败，请重试',
            icon: 'none',
            duration: 1500,
          });
          console.error(err);
        },
      });
    },
  });